﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Data;

using System.Runtime.InteropServices;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Modules.UserDefinedTable;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.UI.Modules;


namespace DotNetNuke.Modules.UserDefinedTable.Security
{


  public class ModuleSecurity
  {
    private Hashtable _settings;
    private bool canEditModuleContent;
    private bool canManageModule;
    private bool hasAddRowPermission;
    private bool hasDeleteRowPermission;
    private bool hasEditPrivateColumnsPermission;
    private bool hasEditRowPermission;
    private bool hasShowAllUserDefinedColumnsPermission;
    private bool hasViewListPermission;
    private bool isOnlyAllowedToManipulateHisOwnData;

    public ModuleSecurity(ModuleInstanceContext context)
      : this(context.ModuleId, context.TabId, context.Settings)
    {
    }

    public ModuleSecurity(int moduleId, int tabId)
      : this(moduleId, tabId, null)
    {
    }

    public ModuleSecurity(int moduleId, int tabId, Hashtable settings)
    {
      ModuleController controller = new ModuleController();
      if (settings == null)
      {
        this.Settings = controller.GetModuleSettings(moduleId);
      }
      else
      {
        this.Settings = settings;
      }
      ModuleInfo module = controller.GetModule(moduleId, tabId);

      if (module != null)
      {
        ModulePermissionCollection modulePermissions = module.ModulePermissions;
        this.hasEditRowPermission = ModulePermissionController.HasModulePermission(modulePermissions, PermissionName.HasEditRowPermission);
        this.hasDeleteRowPermission = ModulePermissionController.HasModulePermission(modulePermissions, PermissionName.HasDeleteRowPermission);
        this.hasAddRowPermission = ModulePermissionController.HasModulePermission(modulePermissions, PermissionName.HasAddRowPermission);
        this.hasEditPrivateColumnsPermission = ModulePermissionController.HasModulePermission(modulePermissions, PermissionName.EditRestricedFieldsPermission);
        this.hasShowAllUserDefinedColumnsPermission = ModulePermissionController.HasModulePermission(modulePermissions, PermissionName.ShowAllUserDefinedColumnsPermission);
        this.canEditModuleContent = ModulePermissionController.CanEditModuleContent(module);
        this.canManageModule = ModulePermissionController.CanManageModule(module);
        this.hasViewListPermission = ModulePermissionController.HasModulePermission(modulePermissions, PermissionName.ShowListPermission);
        this.isOnlyAllowedToManipulateHisOwnData = Utilities.CBoolN(this.Settings[SettingName.EditOnlyOwnItems], false);
      }
    }





    public static string BestUserName(string UserName, int PortalId)
    {
      string cacheKey = string.Format("UDT_BestUserNameFor{0}", UserName);
      string objObject = (string)DataCache.GetCache(cacheKey);

      if ( string.IsNullOrEmpty(objObject) )
      {
        UserInfo userByName = UserController.GetUserByName(PortalId, UserName);
        if (userByName == null)
          objObject = Utilities.CStrN(UserName, "Unknown Account");
        
        else
          objObject = userByName.DisplayName;
        
        int num = 20 * Convert.ToInt32((int)DotNetNuke.Entities.Host.Host.PerformanceSetting);
        DataCache.SetCache(cacheKey, objObject, TimeSpan.FromMinutes((double)num));
      }
      return objObject;
    }





    public static bool HasAddPermissonByQuota(DataTable FieldsTable, DataTable DataTable, int userRecordQuota, string username)
    {
      if (userRecordQuota > 0)
      {
        string str;
        using (DataView view = new DataView(FieldsTable, string.Format("[{0}]='{1}'", FieldsTableColumn.Type, DataTypeNames.UDT_DataType_CreatedBy), "", DataViewRowState.CurrentRows))
        {
          str = Utilities.CStrN(view[0][FieldsTableColumn.Title], "");
        }
        if (DataTable.Columns.Contains(str + DataTableColumn.Appendix_Original))
          str = str + DataTableColumn.Appendix_Original;

        using (DataView view2 = new DataView(DataTable, string.Format("[{0}] = '{1}'", str, username.Replace("'", "''")), "", DataViewRowState.CurrentRows))
        {
          return (view2.Count < userRecordQuota);
        }
      }
      return true;
    }





    public static bool IsAdministrator()
    {
      return PortalSecurity.IsInRole(Globals.GetPortalSettings().AdministratorRoleName);
    }




    public bool IsAllowedToAddRow()
    {
      return (this.canEditModuleContent | this.hasAddRowPermission);
    }





    public bool IsAllowedToAdministrateModule()
    {
      return this.canManageModule;
    }





    public bool IsAllowedToDeleteRow(bool isUsersOwnRow = true)
    {
      return (this.canEditModuleContent | (this.hasDeleteRowPermission & (!this.isOnlyAllowedToManipulateHisOwnData | isUsersOwnRow)));
    }




    public bool IsAllowedToEditAllColumns()
    {
      if ((!this.hasEditPrivateColumnsPermission || !Convert.ToBoolean(this.Settings[SettingName.EditPrivateColumnsForAdmins]) && (!this.canEditModuleContent || !Convert.ToBoolean(this.Settings[SettingName.EditPrivateColumnsForAdmins]) )))
        return false;

      return true;
    }




    public bool IsAllowedToEditRow(bool isUsersOwnRow = true)
    {
      return (this.canEditModuleContent | (this.hasEditRowPermission & (!this.isOnlyAllowedToManipulateHisOwnData | isUsersOwnRow)));
    }




    public bool IsAllowedToSeeAllUserDefinedColumns()
    {
      return (this.hasShowAllUserDefinedColumnsPermission && Convert.ToBoolean(this.Settings[SettingName.ShowAllColumnsForAdmins]));
    }




    public bool IsAllowedToViewList()
    {
      string str = Utilities.CStrN(this.Settings[SettingName.ListOrForm], "Unknown");

      if (str == "Form")
        return (this.canEditModuleContent || (this.hasViewListPermission && Utilities.CBoolN(this.Settings[SettingName.ShowListRequiresPermission], false)));

      if ((str != "FormAndList") && (str != "ListAndForm"))
        return false;

      if (!this.hasViewListPermission && Utilities.CBoolN(this.Settings[SettingName.ShowListRequiresPermission], false))
        return false;

      return true;
    }




    public static string RoleNames(UserInfo User)
    {
      string str2;
      if (User.Roles != null)
        str2 = string.Format("|{0}", string.Join("|", User.Roles));

      else
        str2 = "";

      str2 = str2 + string.Format("|{0}", "All Users");
      if (IsAdministrator())
        str2 = str2 + string.Format("|{0}", Globals.GetPortalSettings().AdministratorRoleName);

      return string.Format("{0}|", str2);
    }





    public static int UserId(string Username, int Portalid)
    {
      string cacheKey = string.Format("UDT_UserIDFor{0}", Username);
      int objObject = Utilities.CIntN(DataCache.GetCache(cacheKey));

      if (objObject == Null.NullInteger)
      {
        UserInfo userByName = UserController.GetUserByName(Portalid, Username);
        if (userByName == null)
          objObject = 0;

        else
          objObject = userByName.UserID;

        int num3 = 20 * Convert.ToInt32((int)DotNetNuke.Entities.Host.Host.PerformanceSetting);
        DataCache.SetCache(cacheKey, objObject, TimeSpan.FromMinutes((double)num3));
      }
      return objObject;
    }




    public Hashtable Settings
    {
      get
      {
        return this._settings;
      }
      set
      {
        this._settings = value;
      }
    }



  }

}

